import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'dart:typed_data';

import 'package:audioplayers/audioplayers.dart';
import 'package:camera/camera.dart';
import 'package:dio/dio.dart' as dio;
import 'package:flutter/services.dart';
import 'package:get/get.dart' as getPack;
import 'package:get/get_rx/get_rx.dart';
import 'package:image_picker/image_picker.dart';
import 'package:path_provider/path_provider.dart';

import '../../../routes/app_pages.dart';

import '../../../utils/tips.dart';

import '../controllers/utilsFile.dart';

AudioPlayer audioPlayer = AudioPlayer();

class PhotoTranslateController extends getPack.GetxController {
  // pageState用于控制应该显示什么内容
  // 相关值说明：
  // pickFromCamera 开启拍照
  // loading // 向后端发送请求
  // result 显示图片翻译结果
  // share 分享
  // gallery 查看所有图片
  var pageState = 'pickFromCamera'.obs;
  var flashStatue = 'off'.obs;
  var picResult = []; //最新图片的翻译结果

  var galleryData = RxList([]); //存储翻译后的图片路径;
  // galleryData包含的内容：
  // tgt:图片+译文 保存起来的路径
  // height
  // width
  // isSelect :是否被选中，
  // {'tgt':'${directory}/${timeStamp}.png','height':picWidth.toDouble(),'width':picHeight.toDouble()}

  // 语言部分：参考 views/controller/indexViewController(以下四个值跟语言选择相关)
  String fromLanFlag = 'zh-CN';
  String toLanFlag = 'en-US';
  var fromLanFlagDisplay = '中文（普通话，中国大陆）'.obs;
  var toLanFlagDisplay = '英语（美国）'.obs;

  bool getPicRes = false; //是否有图片翻译结果（如果有结果切换语言需重新翻译）

  // 最新图片的源语言和目标语言code(语音播放时需要)
  var currentSrc = ''.obs;
  var currentTgt = ''.obs;

  // 拍照部分
  var picPath = ''.obs;
  var picHight=0.0.obs;

  late List<CameraDescription> cameras;
  @override
  Future<void> onInit() async {
    super.onInit();
    // 删除文件夹
    await PhotoUtil.deleteDirectory();
    //  创建文件夹
    await PhotoUtil.createFolder();
  }
  //  语言部分
  void chooseFromLanguages() async {
    final languageItem = await getPack.Get.toNamed(Routes.LANGUAGE_OPINION,arguments: {'code':fromLanFlag});
    fromLanFlag = languageItem['code'];
    fromLanFlagDisplay.value = languageItem['desc'];
    if (getPicRes) {
      var textData = picResult;
      var pureText = textData.map((item) => item['text']).toList();
      translateText(pureText);
    }
  }

  void chooseToLanguages() async {
    final languageItem = await getPack.Get.toNamed(Routes.LANGUAGE_OPINION,arguments: {'code':toLanFlag});
    toLanFlag = languageItem['code'];
    toLanFlagDisplay.value = languageItem['desc'];
    if (getPicRes) {
      var textData = picResult;
      var pureText = textData.map((item) => item['text']).toList();
      translateText(pureText);
    }
  }
  void switchLang(){
    final tempCode = fromLanFlag;
    final tempDesc = fromLanFlagDisplay.value;
    fromLanFlag = toLanFlag;
    fromLanFlagDisplay.value = toLanFlagDisplay.value;
    toLanFlag = tempCode;
    toLanFlagDisplay.value =  tempDesc;
    if (getPicRes) {
      var textData = picResult;
      var pureText = textData.map((item) => item['text']).toList();
      translateText(pureText);
    }
  }

  //  拍照相关逻辑
  //  获取本地照片
  Future uploadLocalImage(screenWidth,context) async {
    final image = await ImagePicker().pickImage(source: ImageSource.gallery);
    if (image == null) return;
    sendImage(image.path, screenWidth,context);
  }

  Future<void> sendImage(path, screenWidth,context) async {
    picPath.value = path;
    picHight.value = await PhotoUtil.getLocalImageHeight(path,screenWidth.toDouble());
    print('picHight${picHight.value}');
    pageState.value = 'loading';
    var transData = await PhotoUtil.fetchTranslate(
      path,
      screenWidth,
      fromLanFlag,
      toLanFlag,
    );
    if (transData != null) {
      print('transData ${transData}');
      picResult = transData as List;
      currentSrc.value = fromLanFlag;
      currentTgt.value = toLanFlag;
      pageState.value = 'result';
      getPicRes = true;
      PhotoUtil.clearVoiceFile();
      return;
    }else{
      PhotoUtil.showCheckDialog(context,clearTempData);
    }
  }

  // 文本翻译
  void translateText(textArray) async {
    if (textArray[0].trim() == '') {
      return;
    }
    pageState.value = 'loading';
    Tips.showLoading();
    dio.Response resp = await dio.Dio().post(
      'https://xy-apis.newtranx.com/mt/v1/text',
      data: {"srcLang": fromLanFlag, "tgtLang": toLanFlag, "texts": textArray},
      options: dio.Options(
        responseType: dio.ResponseType.stream,
        headers: {
          'X-Api-Key': '264e03da4958e5ea405dd8f63b87da898757b821',
          'Content-Type': 'application/json',
        },
      ),
    );
    resp.data?.stream.cast<List<int>>().transform(Utf8Decoder()).listen((
      event,
    ) {
      Map<String, dynamic> contentParams = json.decode(event);
      Tips.dismissLoading();
      if (contentParams['code'] == 200) {
        final resContent = contentParams['data']['content'];
        List textData = picResult;
        for (int i = 0; i < textData.length; i++) {
          var changeText = resContent[i]['text'].replaceAll("'", "\'");
          textData[i]['translation'] = changeText;
        }
        print('newdata ${textData}');
        picResult = textData;
        currentSrc.value = fromLanFlag;
        currentTgt.value = toLanFlag;
        pageState.value = 'result';
        getPicRes = true;
        PhotoUtil.clearVoiceFile();
      } else {
        Tips.showToast('翻译失败，请稍后重试');
      }
    });
  }

  //   文本转语音
  void translateVoice(text, lang) async {
    if (text.trim() == '') {
      return;
    }
    // 查找是否有对应的文件存在
    final dir = await getTemporaryDirectory();
    bool isSrcLang = (lang.trim() == currentSrc.trim());
    print('lang${lang}currentSrc${currentSrc}isSrcLang${isSrcLang}');
    final path = '${dir.path}/audio_temp_${isSrcLang ? 'src' : 'tgt'}.mp3';
    print('checkvoicepath${path}');
    File file = File(path);
    bool exists = await file.exists();
    print('exists${exists}');
    if (exists) {
      audioPlayer.play(DeviceFileSource(path,mimeType: 'audio/mpeg'));
      return;
    }
    Tips.showLoading();
    try {
      dio.Response resp = await dio.Dio().post(
        'https://xy-apis.newtranx.com/speech/v1/tts/basic',
        data: {"lang": lang, "text": text},
        options: dio.Options(
          responseType: dio.ResponseType.stream,
          headers: {
            'X-Api-Key': '264e03da4958e5ea405dd8f63b87da898757b821',
            'Content-Type': 'application/json',
          },
        ),
      );
      resp.data?.stream.listen((event) async {
        bool isSrcLang = (lang.trim() == currentSrc.trim());
        String tempFilePath = await _saveFileToTemp(
          event,
          isSrcLang ? 'src' : 'tgt',
        ); // 保存到临时文件并获取路径
        print('tempFilePath${tempFilePath}');
        audioPlayer.play(DeviceFileSource(tempFilePath,mimeType: 'audio/mpeg'));
        Tips.dismissLoading();
      });
    } catch (e) {
      print('ttserror${e}');
      Tips.dismissLoading();
    }
  }

  Future<String> _saveFileToTemp(Uint8List data, type) async {
    final buffer = data.buffer; // 获取Uint8List的buffer对象
    final bytes = buffer.asUint8List(
      data.offsetInBytes,
      data.length,
    ); // 创建新的Uint8List视图
    final dir = await getTemporaryDirectory(); // 获取临时目录路径
    final file =
        await File('${dir.path}/audio_temp_${type}.mp3').create(); // 创建文件
    await file.writeAsBytes(bytes); // 写入数据到文件
    return file.path; // 返回文件路径
  }

  void changePageState(String pageView) {
    pageState.value = pageView;
  }

  void addPhoto(data) {
    galleryData.add(data);
  }

  void deletePhoto(int index) {
    if (index >= 0 && index < galleryData.length) {
      galleryData.removeAt(index);
    }
  }

  void deleteLastPhoto() {
    final length = galleryData.length;
    if (length > 1) {
      galleryData.removeAt(length - 1);
    }
  }
 void deleteIndexPhoto(int index){
    galleryData.removeAt(index);
 }
  // 删除的逻辑
  void clickDelete(bool isGallery,int index){
    final length = galleryData.length;
    final jumpCamera = length ==1 || !isGallery;
    //  删除当前图片
    if(jumpCamera){
      galleryData.removeAt(length - 1);
      changePageState('pickFromCamera');
     return;
    }
    galleryData.removeAt(index);
  }
  // 返回的时候，清空所有临时数据
  void clearAll() {
    galleryData.clear();
    PhotoUtil.deleteDirectory();
  }

//  识别不出内容时清空临时数据
void clearTempData(){
  pageState.value ='pickFromCamera';
  picPath.value='';
  picHight.value=0.0;
  getPicRes = false;
}
}
